package com.walle.ak47.commons.jaxrs.cxf.interceptor;

import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.XMLMessage;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.walle.ak47.commons.jaxrs.constant.ProtocolParam;
import com.walle.ak47.commons.jaxrs.cxf.header.SecureHander;
import com.walle.ak47.commons.jaxrs.cxf.header.SecureHeaderHolder;

public class AttributesHanderInterceptor  extends AbstractPhaseInterceptor<XMLMessage> {

	@SuppressWarnings("unused")
	private static final Logger LOG = LoggerFactory.getLogger(AttributesHanderInterceptor.class);

	public AttributesHanderInterceptor() {
		super(Phase.PRE_INVOKE);// 该拦截器在调用前拦截HttpHeader信息
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void handleMessage(XMLMessage msg) throws Fault {
		try {
			TreeMap<String, List> headers = (TreeMap<String, List>) msg.get(Message.PROTOCOL_HEADERS);
			List list = (List) headers.get(ProtocolParam.TOKEN_HEADER);
			if (list == null || list.size() == 0) {
				throw new Exception("【X-AUTH-HEADER头校验】不存在!");
			}
			String xAuthHeader = list.get(0).toString();

			SecureHander header = SecureHeaderHolder.getHeader() ;
			header.getAttrs().put( ProtocolParam.TOKEN_HEADER, xAuthHeader ) ;
			HttpServletRequest request = (HttpServletRequest) msg.get(AbstractHTTPDestination.HTTP_REQUEST);
			header.getAttrs().put( "remoteAddr", request.getRemoteAddr() ) ;

		} catch (Exception e) {
			throw new Fault(new IllegalAccessException(e.getMessage()));
		}

	}
}
